package com.itheima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.model.common.VO.HotArticleVo;
import com.heima.model.common.admin.pojos.AdChannel;
import com.heima.model.common.artcle.pojo.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.service.HotArticleService;
import com.itheima.common.constants.message.ArticleConstants;
import com.itheima.common.exception.CustException;
import com.itheima.feigns.AdminFeign;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //计算热点文章

    @Override
    public void computeHotArticle() {
//        - 定时任务每天凌晨1点，查询前5天的文章
        String dateTime = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticle> apArticles = apArticleMapper.selectArticleByDate(dateTime);
//                - 计算每个文章的分值，其中不同的行为设置不同的权重
        //  （阅读：1，点赞：3，评论：5，收藏：8）
        List<HotArticleVo> hotArticleVos = getArticlesScore(apArticles);
//        - 按照分值排序，给每个频道找出分值较高的30条数据，存入缓存中
        SaveToRedis(hotArticleVos);



 
    }

    @Override
    public void updateApArticle(AggBehaviorDTO mess) {
        //1 查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (mess.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (mess.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (mess.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (mess.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        apArticleMapper.updateById(apArticle);
        //3 计算文章分值
        List<ApArticle> apArticles= new ArrayList<>();
        apArticles.add(apArticle);
        List<HotArticleVo> scores = getArticlesScore(apArticles);
        Integer score = scores.get(0).getScore(); 
        // 如果是今天发布的文章，热度*3
        String publishStr = DateUtils.dateToString(apArticle.getPublishTime());
        String nowStr = DateUtils.dateToString(new Date());

        if (publishStr.equals(nowStr)){
            score = score*3;
            //当天热点数据 *3
        }
        //4 更新缓存（频道）
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //5 更新推荐列表的缓存
        updateArticleCache(apArticle, score,  ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ ArticleConstants.DEFAULT_TAG);
    }
    /**
     * 更新文章缓存
     * @param apArticle  当前文章
     * @param score 分数
     * @param cacheKey
     */
    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        boolean flag = false;
        String hotArticleListJson = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(hotArticleListJson)) {
            List<HotArticleVo> hotArticleList = JSONArray.parseArray(hotArticleListJson,HotArticleVo.class);
            //1 如果当前缓存中有当前文章，更新分值
            for (HotArticleVo hotArticleVo : hotArticleList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }
            //2 缓存中没有当前文章
            if (!flag) {
                HotArticleVo hotArticle = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticle);
                hotArticle.setScore(score);
                hotArticleList.add(hotArticle);
            }
            //3. 将热点文章集合 按得分降序排序  取前30条缓存至redis中
            hotArticleList = hotArticleList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleList));
        }
    }

    private void SaveToRedis(List<HotArticleVo> hotArticleVos) {
        //查找所有的频道
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        //将文章按照频道id分组  并存入redis
        if (responseResult.checkCode()){
            List<AdChannel> channels = responseResult.getData();
            for (AdChannel channel : channels) {
                List<HotArticleVo> articleVos = hotArticleVos.stream().filter(hotArticleVo -> hotArticleVo.getChannelId().equals(channel.getId())).collect(Collectors.toList());
                SortAndSave(articleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channel.getId());

            }
        }
        //给推荐频道存入  所有的文章进行排序最前面的30条
        SortAndSave(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);



    }

    private void SortAndSave(List<HotArticleVo> articleVos, String s) {
        //排序
        List<HotArticleVo> hotArticleVos = articleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
        //存入
        redisTemplate.opsForValue().set(s, JSON.toJSONString(hotArticleVos));
    }

    private List<HotArticleVo> getArticlesScore(List<ApArticle> apArticles) {
        //计算各个文章的分值
        return apArticles.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            int score =0;
            if (apArticle.getLikes()!=null || apArticle.getLikes()!=0){
                score += apArticle.getLikes()*3;
            }
            if (apArticle.getViews()!=null || apArticle.getViews()!=0){
                score = score + apArticle.getViews();
            }
            if (apArticle.getCollection()!=null || apArticle.getCollection()!=0){
                score += apArticle.getCollection()*8;
            }
            if (apArticle.getComment()!=null || apArticle.getComment()!=0){
                score += apArticle.getComment()*5;
            }
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }
}
